package com.zhugang.queue;

/**
 * @program algorithms
 * @description: 动态扩容的队列
 * @author: chanzhugang
 * @create: 2022/02/22 23:51
 */
public class DynamicArrayQueue {

    private final String[] array;
    private final int n;
    private int head;
    private int tail;

    public DynamicArrayQueue(int capacity) {
        this.array = new String[capacity];
        this.n = capacity;
        this.head = 0;
        this.tail = 0;
    }


    /**
     * 入队
     *
     * @param data
     * @return
     */
    public boolean enqueue(String data) {
        if (tail == n) {
            if (head == 0) {
                // 队列满了
                return false;
            }
            for (int i = head; i < tail; i++) {
                // 数据搬移
                array[i - head] = array[i];
            }
            // 更新头、尾下标
            tail -= head;
            head = 0;
        }
        array[tail] = data;
        tail++;
        return true;

    }

    /**
     * 出队
     *
     * @return
     */
    public String dequeue() {
        if (head == tail) {
            // 队空
            return null;
        }
        String data = array[head];
        head++;
        return data;
    }
}